package org.inspiration.dudu.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Component
public class ImageUtil {

    @Value("${dudu.file.upload-path}")
    private String uploadPath;

    /**
     * 根据文件名获取图片
     * @param filename
     * @return
     */
    public  ResponseEntity<byte[]> getImage(String filename) {
        try {
            // 创建 Path 对象
            Path path = Paths.get(uploadPath, "images", filename);
            if (!Files.exists(path)) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            // 读取文件内容
            byte[] imageBytes = Files.readAllBytes(path);

            // 获取文件后缀并确定 Content-Type
            String contentType = getContentTypeFromFilename(filename);
            if (contentType == null) {
                return new ResponseEntity<>(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(imageBytes.length);

            // 返回响应
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据图片后缀获取ContentType
     * @param filename
     * @return
     */
    private static String getContentTypeFromFilename(String filename) {
        int lastIndex = filename.lastIndexOf('.');
        if (lastIndex == -1) {
            return null;
        }
        String extension = filename.substring(lastIndex + 1).toLowerCase();
        return switch (extension) {
            case "jpg", "jpeg" -> "image/jpeg";
            case "png" -> "image/png";
            case "gif" -> "image/gif";
            case "bmp" -> "image/bmp";
            default -> null;
        };
    }
}